import base64
import json
import pickle

from django import http
from django.contrib import messages
from django.shortcuts import render, redirect, reverse

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.goods.models import SKU, SKUImage
from utils import constants
from utils.response_code import RETCODE


class CartsView(View):
    """购物车管理"""

    def post(self, request):
        """添加购物车"""
        # 获取参数
        json_dict = json.loads(request.body.decode())
        count = json_dict.get('count')
        selected = json_dict.get("selected")
        sku_id = json_dict.get('sku_id')
        print(request.user.id, '-----------------------0000')
        image = SKUImage.objects.filter(sku=sku_id)
        # 判断是否缺少参数
        if not all([count, sku_id]):
            return http.HttpResponseBadRequest('缺少参数')
        # 判断count是否是整数
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseBadRequest('参数count有误')
        # 判断selected是否有勾选
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseBadRequest('参数selected有误')
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            # 如果登录从redis数据库取出数据
            cart_conn = get_redis_connection('carts')
            # 创建管道
            p1 = cart_conn.pipeline()
            # 创建数据
            p1.hincrby('carts_%s' % user.id, sku_id, count)
            # 创建selected
            if selected:
                p1.sadd('selected_%s' % user.id, sku_id)
            # 执行管道
            p1.execute()
            return http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
        else:
            # 如果用户没有登录就将数据存入cookie中
            redis_str = request.COOKIES.get('carts')
            # 判断cookie中是否有数据
            if redis_str:
                # 如果有就将数据转为字典
                carts_dict = pickle.loads(base64.b64decode(redis_str.encode()))
            else:
                carts_dict = {}

            # 判断字典中是否有之前添加的商品
            if sku_id in carts_dict:
                # 将商品进行添加加和
                origin_count = carts_dict[sku_id]['count']
                count += origin_count

            carts_dict[sku_id] = {
                'count':count,
                'selected': selected,
            }
            cookie_dict = base64.b64encode(pickle.dumps(carts_dict)).decode()

            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '添加购物车成功'})
            response.set_cookie('carts', cookie_dict, max_age=constants.CARTS_COOKIE_EXPIRES)
            return response

    def get(self, request):
        """展示购物车"""
        user = request.user

        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            redis_conn = get_redis_connection('carts')
            # 获取redis中的购物车数据
            redis_cart = redis_conn.hgetall('carts_%s' % user.id)
            # 获取redis中的选中状态
            # cart_selected = redis_conn.smembers('selected_%s' % user.id)

            # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
            cart_dict = {}
            for sku_id, count in redis_cart.items():
                cart_dict[int(sku_id)] = {
                    'count': int(count),
                    # 'selected': sku_id in cart_selected
                }
        else:
            # 用户未登录，查询cookies购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

        # 构造购物车渲染数据
        sku_ids = cart_dict.keys()

        skus = SKU.objects.filter(id__in=sku_ids)



        cart_skus = []
        for sku in skus:
            cart_skus.append({
                'id': sku.id,
                'name': sku.name,
                'count': cart_dict.get(sku.id).get('count'),
                'default_image_url': sku.default_image,
                'price': str(sku.price),  # 从Decimal('10.2')中取出'10.2'，方便json解析
                'amount': str(sku.price * cart_dict.get(sku.id).get('count')),
            })
        a = []
        for x in skus:
            # print(x['id'])
            a.append(x.id)
        print(a)
        context = {
            'cart_skus': cart_skus,
            'a': a
            # 'type_name': type_name,
        }
        print(cart_skus, '0000000000000000000000000001213')
        # 渲染购物车页面
        return render(request, 'cart.html', context)


class del_Cart(View):
    def get(self, request):
        sku_id = request.GET.get('id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            messages.success(request, "缺少参数")
            return redirect(reverse('shoppingcart:carts'))
            # 判断用户是否登录
        user = request.user
        if user is not None and user.is_authenticated:
            # 用户登录 删除Redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()

            # 删除整条数据
            pl.hdel('carts_%s' % user.id, sku_id)

            pl.execute()
            #  返回数据
            messages.success(request, "删除成功")
            return redirect(reverse('shoppingcart:carts'))

        else:
            # 用户未登录，删除cookie购物车
            cart_str = request.COOKIES.get('carts')
            if cart_str:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                cart_dict = pickle.loads(base64.b64decode(cart_str.encode()))
            else:
                cart_dict = {}

            # 创建响应对象
            response = http.JsonResponse({'code': RETCODE.OK, 'errmsg': '删除购物车成功'})
            if sku_id in cart_dict:
                del cart_dict[sku_id]
                # 将字典转成bytes,再将bytes转成base64的bytes,最后将bytes转字符串
                cookie_cart_str = base64.b64encode(pickle.dumps(cart_dict)).decode()
                # 响应结果并将购物车数据写入到cookie
                response.set_cookie('carts', cookie_cart_str, max_age=constants.CARTS_COOKIE_EXPIRES)
            messages.success(request, "删除成功")
            return redirect(reverse('shoppingcart:carts'))
